<template>
  <div class="main">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <div class="search">
        <el-form-item label="连接名" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入连接名搜索" clearable></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="dbType">
          <el-select v-model="queryParams.dbType" placeholder="请选择数据源类型搜索" clearable>
            <el-option label="mysql" value="mysql"></el-option>
            <el-option label="clickhouse" value="clickhouse"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主机" prop="host">
          <el-input v-model="queryParams.host" placeholder="请输入主机搜索" clearable></el-input>
        </el-form-item>
      </div>
      <div class="search">
        <el-form-item label="账号" prop="username">
          <el-input v-model="queryParams.username" placeholder="请输入账号搜索" clearable></el-input>
        </el-form-item>
        <el-form-item label="数据库名" prop="dbName">
          <el-input v-model="queryParams.dbName" placeholder="请输入数据库名搜索" clearable></el-input>
        </el-form-item>
        <el-form-item label="创建人" prop="createUser">
          <el-input v-model.trim="queryParams.createUser" placeholder="请输入创建人名称搜索" clearable/>
        </el-form-item>
      </div>
      <div class="search">
        <el-button type="primary" @click="restList(query.keywords)" icon="el-icon-search">查询</el-button>
        <el-button @click="refresh('queryForm')" icon="el-icon-refresh">重置</el-button>
      </div>
    </el-form>
    <div class="create-btn">
      <el-button type="primary" icon="el-icon-plus" @click="openDialog('新建数据源')" v-permission="'dataSource:add'">新建数据源</el-button>
    </div>
    <div class="create-btn">
      <el-table :data="tableData" element-loading-spinner="el-icon-loading" element-loading-text="加载中。。。"
                element-loading-custom-class="equipment-loading" element-loading-background="rgba(55,55,55,0.2)"
                height="calc(100vh - 375px)">
        <el-table-column prop="name" label="数据源名称"></el-table-column>
        <el-table-column prop="dbType" label="数据源类型"></el-table-column>
        <el-table-column prop="host" label="主机"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="port" label="端口"></el-table-column>
        <el-table-column prop="dbName" label="数据库"></el-table-column>
        <el-table-column prop="createUser" label="创建人" width="120"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="150"></el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button @click="openDialog('编辑数据源',scope.row)" type="text" v-permission="'dataSource:update'">编辑</el-button>
            <el-popconfirm
              @onConfirm="handleDelete(scope.row)"
              confirm-button-text='确定'
              cancel-button-text='我再看看'
              icon="el-icon-info"
              icon-color="red"
              title="是否确认删除？"
            >
              <el-button slot="reference" type="text" v-permission="'dataSource:delete'">删除</el-button>
            </el-popconfirm>
            <el-button @click="toForward(scope.row)" type="text" v-permission="'dataSource:connect'">数据生成</el-button>

          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="query.pageNum"
        :limit.sync="query.pageRow"
        layout="total, prev, pager, next"
        :hide-on-single-page="value"
        @pagination="getDataSourceList"
      />
    </div>
    <cu-dialog :dialogVisble="visible" :title="title" :editData="editData" @closeDialog="closeDialog"
               @refreshList="restList"></cu-dialog>
  </div>
</template>

<script>
import {getConnectApi} from '@/api/api'

import Pagination from "@/components/Pagination/index";
import CuDialog from "./cuDialog";

export default {
  name: "DataSource",
  components: {Pagination, CuDialog},
  data() {
    return {
      queryParams: {
        name: "",
        dbType: "",
        createUser: "",
        username: "",
        dbName: "",
        host: "",
        userId: this.$store.getters.userId
      },
      tableData: [],
      query: {
        pageRow: 10,
        pageNum: 1
      },
      value: false,
      total: 0,
      visible: false,
      title: "",
      editData: {}
    };
  },
  mounted() {
    this.getDataSourceList();
  },
  methods: {
    refresh(queryForm) {
      this.$refs[queryForm].resetFields();
      this.getDataSourceList();
    },
    restList() {
      this.query.pageNum = 1;
      this.getDataSourceList();
      this.closeDialog()
    },
    getDataSourceList() {
      this.query = {...this.query, ...this.queryParams}
      this.api({
        url: "/getDataSourceList",
        method: "post",
        data: this.query
      }).then(resp => {
        this.tableData = resp.list;
        this.total = resp.totalCount;
      });
    },
    openDialog(title, data = null) {
      this.title = title;
      this.visible = true;
      this.editData = data ? data : {}
    },
    closeDialog() {
      this.visible = false;
    },
    handleDelete(data) {
      this.api({url: `/deleteDataSource/${data.id}`, method: "delete"}).then((resp) => {
        this.getDataSourceList()
        this.$message({message: resp, type: 'success'});
      })
    },
    async toForward(data) {
      const loading = this.$loading({
        lock: true, // lock的修改符--默认是false
        text: 'Loading', // 显示在加载图标下方的加载文案
        spinner: 'el-icon-loading', // 自定义加载图标类名
        background: 'rgba(0, 0, 0, 0.7)', // 遮罩层颜色
        target: document.querySelector('#table')//loading覆盖的dom元素节点
      })
      let resp = await getConnectApi(data)
      delete data.createTime
      delete data.createUser
      delete data.updateTime
      delete data.updateUser
      delete data.updateUser
      if (resp.code !== "500") {
        if (resp === "操作成功") {
          this.$message.warning("当前数据源下不存在表，请先创建表")
        } else {
          this.$router.push({name: 'dataGenerate', params: {tables: resp, dbInfo: data}})
          sessionStorage.setItem("tables", JSON.stringify(resp))
          sessionStorage.setItem("dbInfo", JSON.stringify(data))
        }
      }
      loading.close()
    }
  }
};
</script>
<style scoped>
.main {
  height: calc(100vh - 110px);
  padding: 20px;
  background-color: white;
  margin: 20px;
}

.search {
  margin: auto;
  text-align: center;
}

.create-btn {
  margin-top: 10px;
}
</style>
